import wxValidate from 'wechat-validate'
Page({
  onLoad({redirectURL}){
    this.redirectURL = redirectURL
  },
  data: {
    countDownVisible: false,
    mobile: '',
    code: ''
  },
  // 将插件注入到页面实例中
  behaviors: [wxValidate],
  rules: {
    mobile: [{
        required: true,
        message: '请填写手机号码!'
      },
      {
        pattern: /^1[3-8]\d{9}$/,
        message: '请填写正确的手机号码!'
      },
    ],
    code: [{
        required: true,
        message: '请填写验证码!'
      },
      {
        pattern: /^\d{6}$/,
        message: '请填写正确的验证码!'
      },
    ]
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  async getSMSCode() {
    //校验数据的合法性
    const {
      valid,
      message
    } = this.validate('mobile')
    // 如果验证不合法则不再执行后面的逻辑
    if (!valid) return wx.utils.toast(message)
    this.setData({
      // 点击后启用倒计时组件
      countDownVisible: true
    })
    //调用网络获取验证码
    const {code} = await wx.http.get('/code', {
      mobile: this.data.mobile
    })
    wx.utils.toast(code)
    console.log(code)
  },
  //登录
  async submitForm() {
    //校验数据合法性
    if (!this.validate()) return
    // 调用登录接口
    const {
      token,
      refreshToken
    } = await wx.http.post('/login', {
      mobile: this.data.mobile,
      code: this.data.code,
    })
    //登录成功，保存token
    // console.log(token)
    // console.log(refreshToken)
    getApp().setToken('token',token)
    getApp().setToken('refreshToken',refreshToken)
    console.log(this.redirectURL)
     // 重定向
     wx.redirectTo({ url: this.redirectURL })
  }
})